﻿var dragType;
var buildType;
var isBuild = false;
var widthSequence = 170;
var widthPlacehoder = 40;
var widthWill = 70;

var clone;
var cloneHtml;

var activity;

jQuery(function ()
{
    buildDraggable();
    buildDropTarget();

    $("#handlertype").change(function ()
    {
        handlersPicker();
    });
});

function buildDraggable()
{
    $("#tool div").each(function ()
    {
        var control = this;
        $(control).kendoDraggable({
            hint: function ()
            {
                clone = $(control).clone();
                return clone;
            },
            dragstart: draggableOnDragStart,
            dragend: draggableOnDragEnd
        });
    });
}

function buildDropTarget()
{
    $(".container").find(".placehoder").each(function ()
    {
        $(this).kendoDropTarget({
            dragenter: droptargetOnDragEnter,
            dragleave: droptargetOnDragLeave,
            drop: droptargetOnDrop
        });
    });

    $(".container").find(".handle,.sequence,.parallel").click(function (e)
    {
        e.stopPropagation();
        select(this);
    });
}

function clearWill()
{
    if (cloneHtml)
    {
        clone.html(cloneHtml);
        cloneHtml = null;
    }

    $(".container").find(".placehoder").each(function ()
    {
        $(this).html(getTemplate("placehoder"));
    });
}

function handlersPicker()
{
    var handlertype = $("#handlertype").val();

    $(".handlersPicker").addClass("hide");
    if (handlertype == "Employee")
    {
        $("#trEmployee").removeClass("hide");
    }
    else if (handlertype == "DepartmentManager" || handlertype == "DepartmentEmployee")
    {
        $("#trDepartment").removeClass("hide");
    }
    else if (handlertype == "TeamManager" || handlertype == "TeamMember")
    {
        $("#trTeam").removeClass("hide");
    }
    else if (handlertype == "Post")
    {
        $("#trPost").removeClass("hide");
    }
    else if (handlertype == "Role")
    {
        $("#trRole").removeClass("hide");
    }
}

function removee()
{
    var type = $(activity).attr("data-type");
    var parentType = $(activity).parent().attr("data-type");
    if (isSequence(type) && $(activity).parent().find(".sequence").length == 2)
    {
        alert("不能少于两个分支");
    }
    else if (isSequence(parentType) && $(activity).parent().find(".handle").length == 1)
    {
        alert("分支中不能少于一个活动");
    }
    else
    {
        $(activity).next().remove();
        $(activity).remove();
    }

    $("#property").find(".form").hide();
}

function modify()
{
    var type = $(activity).attr("data-type");
    if (type == "handle")
    {
        $(activity).html($("#displayname").val());
        $(activity).attr("data-displayname", $("#displayname").val());

        //设置处理方式
        $(activity).attr("data-handlemode", $("#handlemode").val());

        //设置处理人类型
        var handlertype = $("#handlertype").val();
        $(activity).attr("data-handlertype", handlertype);

        //设置处理人
        if (
                handlertype == "Employee" ||
                handlertype == "DepartmentManager" || handlertype == "DepartmentEmployee" ||
                handlertype == "TeamManager" || handlertype == "TeamMember" ||
                handlertype == "Post" ||
                handlertype == "Role"
                )
        {
            $(activity).attr("data-handlers", $(".handlersPicker:visible :hidden[name='handlers']").val().replace(/"/g, "'"));
        }
        else
        {
            $(activity).attr("data-handlers", "");
        }

        //设置处理操作
        var handleoperation = "";
        if ($("#handleOperation_ReturnPrev")[0].checked)
        {
            handleoperation += "ReturnPrev" + ",";
        }
        if ($("#handleOperation_ReturnApply")[0].checked)
        {
            handleoperation += "ReturnApply" + ",";
        }
        if ($("#handleOperation_HandleCompleted")[0].checked)
        {
            handleoperation += "HandleCompleted" + ",";
        }
        if (handleoperation.length > 0)
        {
            handleoperation = handleoperation.substring(0, handleoperation.length - 1);
        }
        $(activity).attr("data-handleoperations", handleoperation);

        //权限
        $(activity).attr("data-power", $("#power").val());
    }
    else if (type == "sequenceSwitch")
    {
        $(activity).attr("data-condition", $("#condition").val());
    }
}

function select(element)
{
    activity = element;

    $(".container").find(".handle,.sequence,.parallel").removeClass("selected");
    $(activity).addClass("selected");

    $("#property").find(".form").hide();
    var type = $(activity).attr("data-type");
    if (type == "begin")
    {
        $("#property").find("[role=begin]").show();
    }
    else if (type == "end")
    {
    }
    else if (type == "handle")
    {
        $("#property").find("[role=handle]").show();

        $("#displayname").val($(activity).attr("data-displayname"));
        $("#handlemode").data("kendoDropDownList").value($(activity).attr("data-handlemode"));
        $("#handlertype").data("kendoDropDownList").value($(activity).attr("data-handlertype"));
        handlersPicker();

        var handlertype = $("#handlertype").val();
        if (
                handlertype == "Employee" ||
                handlertype == "DepartmentManager" || handlertype == "DepartmentEmployee" ||
                handlertype == "TeamManager" || handlertype == "TeamMember" ||
                handlertype == "Post" ||
                handlertype == "Role"
                )
        {
            $(".handlersPicker:visible :hidden[name='handlers']").val($(activity).attr("data-handlers"));
            $(".handlersPicker:visible :hidden[name='handlers']").trigger("change");
        }

        //处理操作
        var handleoperation = $(activity).attr("data-handleoperations");
        $("#handleOperation_ReturnPrev").attr("checked", false);
        $("#handleOperation_ReturnApply").attr("checked", false);
        $("#handleOperation_HandleCompleted").attr("checked", false);
        if (handleoperation.indexOf("ReturnPrev") >= 0)
        {
            $("#handleOperation_ReturnPrev").attr("checked", true);
        }
        if (handleoperation.indexOf("ReturnApply") >= 0)
        {
            $("#handleOperation_ReturnApply").attr("checked", true);
        }
        if (handleoperation.indexOf("HandleCompleted") >= 0)
        {
            $("#handleOperation_HandleCompleted").attr("checked", true);
        }

        //处理权限
        $("#power").val($(activity).attr("data-power"));
    }
    else if (type == "sequenceSwitch")
    {
        $("#property").find("[role=sequenceSwitch]").show();

        $("#condition").val($(activity).attr("data-condition"));
    }
    else
    {
        $("#property").find("[role=sequence]").show();
    }
}

function isComplex(type)
{
    return type == "parallel" || type == "pick" || type == "switch";
}
function isSequence(type)
{
    if (type) return type.indexOf("sequence") >= 0;
    return false;
}

function draggableOnDragStart(e)
{
    dragType = $(e.currentTarget).attr("role");
}
function droptargetOnDragEnter(e)
{
    isBuild = false;

    var parentType = $(e.dropTarget).parent().attr("data-type");
    if (isComplex(dragType) && (isComplex(parentType) || isSequence(parentType)))
    {
        cloneHtml = clone.html();
        clone.html("不能在分支活动里再加入分支");
        return;
    }
    if (parentType == "parallel" || parentType == "pick")
    {
        buildType = "sequenceParallel";
    }
    else if (parentType == "switch")
    {
        buildType = "sequenceSwitch";
    }
    else
    {
        buildType = dragType;
    }

    var will = getTemplate("will");
    $(e.dropTarget).html(will);
    isBuild = true;
}

function droptargetOnDragLeave(e)
{
    clearWill();
}

function droptargetOnDrop(e)
{
    if (!isBuild) return;

    clearWill();

    if (buildType == "sequenceParallel" || buildType == "sequenceSwitch")
    {
        var countSequence = $(e.dropTarget).parent().find(">.sequence").length;
        var countPlacehoder = $(e.dropTarget).parent().find(">.placehoder").length;
        var width = widthSequence * (countSequence + 1) + widthPlacehoder * (countPlacehoder + 1) + widthWill;
        $(e.dropTarget).parent().width(width);
    }

    $(e.dropTarget).after(getTemplate(buildType));
    buildDropTarget();

    select($(e.dropTarget).next());
    isBuild = false;
}

function draggableOnDragEnd(e)
{
}

function getTemplate(type)
{
    return $("#template").find("div[role='" + type + "']").html()
}

function pad(num, n)
{
    y = '00000000000000000000000000000' + num;
    return y.substr(y.length - n);
}

function getActivityXml()
{
    $(".container").find(".handle,.sequence,.parallel").removeClass("selected");

    //遍历一级活动
    var firstXml = "";
    var xml = "";
    $(".container").children(".handle,.parallel").each(function (i)
    {
        var first = this;
        var firstType = $(first).attr("data-type");
        xml = getXml(firstType)

        if (firstType == "handle")
        {
            var step = pad(i, 2);
            $(first).attr("step", step);

            xml = xml
                    .replace(/%Step%/g, step)
                    .replace(/%DisplayName%/g, $(first).attr("data-displayname"))
                    .replace(/%HandleMode%/g, $(first).attr("data-handlemode"))
                    .replace(/%HandlerType%/g, $(first).attr("data-handlertype"))
                    .replace(/%Handlers%/g, $(first).attr("data-handlers"))
                    .replace(/%HandleOperations%/g, $(first).attr("data-handleoperations"));

            firstXml += xml;
        }
        else if (firstType == "begin")
        {
            firstXml += xml;
        }
        else if (firstType == "end")
        {
            firstXml += xml;
        }
        else
        {
            var step = pad(i, 2);
            $(first).attr("step", step);

            xml = xml
                    .replace(/%Step%/g, step);

            firstXml += xml;

            //遍历分支活动
            var secondXml = "";
            $(first).children(".sequence").each(function (j)
            {
                var second = this;
                //var secondType = $(second).attr("data-type");
                secondXml += getXml("sequence");

                //遍历分支子活动
                var thirdXml = "";
                $(second).children(".handle").each(function (k)
                {
                    var third = this;
                    //var thirdType = $(third).attr("data-type");

                    var stepSetp = pad(i, 2) + pad(j, 2) + pad(k, 2);
                    $(third).attr("step", stepSetp);

                    xml = getXml("handle");
                    xml = xml
                            .replace(/%Step%/g, stepSetp)
                            .replace(/%DisplayName%/g, $(third).attr("data-displayname"))
                            .replace(/%HandleMode%/g, $(third).attr("data-handlemode"))
                            .replace(/%HandlerType%/g, $(third).attr("data-handlertype"))
                            .replace(/%Handlers%/g, $(third).attr("data-handlers"))
                            .replace(/%HandleOperations%/g, $(third).attr("data-handleoperations"));

                    thirdXml += xml;
                });

                if (firstType == "pick")
                {
                    secondXml = secondXml.replace(/%Handles%/g, thirdXml + getXml("assign"));
                }
                else
                {
                    secondXml = secondXml.replace(/%Handles%/g, thirdXml);
                }
            });

            firstXml = firstXml.replace(/%Branches%/g, secondXml);
        }

    });

    var flowchart = getXml("flowchart");
    flowchart = flowchart.replace(/%Activities%/g, firstXml);

    return flowchart;
}

function getXml(type)
{
    return $("#xml").find("pre[role='" + type + "']").html().replace("<!--", "").replace("-->", "");
}